<template>
  <div class="role-div">
    <el-form :model="searchParam" label-width="70px" size="small">
      <el-form-item label="关键字">
        <el-input
          style="width: 30%"
          placeholder="用户名、姓名、手机号"
          v-model="searchParam.keyword"
        />
        <!-- 日期 -->
        <div class="block">
          <span class="demonstration">创建时间</span>
          <el-date-picker
            v-model="datas"
            value-format="YYYY-MM-DD"
            type="daterange"
            unlink-panels
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
            :shortcuts="shortcuts"
          />
        </div>
      </el-form-item>
      <el-row style="display: flex; margin-bottom: 10px">
        <el-button type="primary" @click="loadData" size="small">
          搜索
        </el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
    <!-- 添加按钮 -->
    <div class="post-div">
      <el-button size="small" type="success" @click="addShow">添加</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="userList" style="width: 100%">
      <el-table-column prop="username" label="用户名" width="100" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="phone" label="手机" width="200" />
      <el-table-column prop="avatar" label="头像" width="100">
        <template #default="scope">
          <img
            :src="scope.row.avatar"
            style="width: 50px; height: 50px"
            width="100"
          />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <span>{{ +scope.row.status === 0 ? '禁用' : '正常' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            size="warning"
            type="warning"
            @click="handleAssign(scope.row)"
          >
            分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[1, 2, 3, 5, 10]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="loadData"
      @current-change="loadData"
      style="margin-top: 20px"
    />
    <!-- 修改|添加用户弹框 -->
    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form :model="form">
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>

        <el-form-item v-if="form.id === 0" label="密码" label-width="120px">
          <el-input v-model="form.password" autocomplete="off" />
        </el-form-item>

        <!-- 文件上传 -->
        <el-form-item label="用户头像" label-width="150px">
          <el-upload
            class="avatar-uploader"
            name="file"
            :headers="headers"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="uploadError"
          >
            <img v-if="userList.avatar" :src="userList.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="姓名" label-width="120px">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>

        <el-form-item label="手机" label-width="120px">
          <el-input v-model="form.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="描述" label-width="120px">
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOrUpdate">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配角色弹框 -->
    <el-dialog v-model="dialogShowRole" title="分配角色">
      <el-form :model="form">
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="form.username" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="角色列表" label-width="120px">
          <!--  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
            全选
          </el-checkbox> -->
          <el-checkbox-group v-model="roleIds" size="small">
            <el-checkbox
              v-for="role in roleList"
              :key="role.id"
              :label="role.id"
              :checked="role.checked"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = dialogShowRole = false">
            取消
          </el-button>
          <el-button type="primary" @click="updateRoleList">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { GetUserList, DeleteUser, SaveUser, UpdateUser } from '@/api/sysUser.js'
import { AssignRole, updateAssignRoles } from '@/api/sysRole'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useApp } from '@/pinia/modules/app'

//查询参数
let pageSize = ref(5)
let pageNum = ref(1)
let total = ref(0)
let searchParam = ref({
  keyword: '',
  beginTime: '',
  endTime: '',
})

let searchParam1 = {
  keyword: '',
  beginTime: '',
  endTime: '',
}
// 表格
const userList = ref([])

//日期选择器数据变量
const datas = ref([])

//页面挂载时加载数据
const loadData = async () => {
  //验证时间有没有值
  if (datas.value && datas.value.length === 2) {
    searchParam.value.beginTime = datas.value[0]
    searchParam.value.endTime = datas.value[1]
  }
  const { data } = await GetUserList(
    pageNum.value,
    pageSize.value,
    searchParam.value
  )
  userList.value = data.list
  total.value = data.total
}

onMounted(() => {
  loadData()
})
//分配角色
const dialogShowRole = ref(false)
const roleIds = ref([])
const roleList = ref([])
const handleAssign = async row => {
  //清空数据
  roleIds.value = []
  roleList.value = []
  dialogShowRole.value = true
  form.value = row
  const { data } = await AssignRole(row.id)
  //  console.log(data);
  roleList.value = data
}
const updateRoleList = async () => {
  dialogShowRole.value = false
  // console.log(roleIds.value)
  await updateAssignRoles(roleIds.value, form.value.id)
}

//文件上传
const uploadUrl = ref('http://127.0.0.1:8081/admin/system/file/upload/avatar')
const { authorization } = useApp()
const headers = { token: authorization.token }
//成功
const handleAvatarSuccess = (respose, uploadFile) => {
  if (+respose.code === 200) {
    userList.value.avatar = respose.data
    form.value.avatar = respose.data
    // console.log(userList.value.avatar)
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(respose.message)
  }
}
//失败
const uploadError = (error, uploadFile) => {
  ElMessage.error('网络连接失败')
}
//弹框
const title = ref('新增用户')
const dialogFormVisible = ref(false)
//重置按钮点击事件
const resetData = () => {
  datas.value = []
  Object.assign(searchParam.value, searchParam1)
  loadData()
}

//表单数据
let form = ref({
  username: '',
  password: '',
  name: '',
  phone: '',
  avatar: '',
  description: '',
  id: 0,
})
let form1 = {
  username: '',
  password: '',
  name: '',
  phone: '',
  avatar: '',
  description: '',
  id: 0,
}
//删除指定角色
const handleDelete = row => {
  ElMessageBox.confirm(`确认删除用户【${row.username}】吗?`, 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      await DeleteUser(row.id)
      loadData()
    })
    .catch(() => {
      ElMessage({
        type: 'success',
        message: '取消删除',
      })
    })
}
//添加角色||修改角色
//添加角色
const addShow = () => {
  dialogFormVisible.value = true
  //清空数据
  Object.assign(form.value, form1)
  title.value = '新增用户'
}
//修改角色
const handleEdit = row => {
  dialogFormVisible.value = true
  Object.assign(form.value, row)
  title.value = '修改用户'
  userList.value.avatar = row.avatar
  // form.value = form1
}
const handleSaveOrUpdate = async () => {
  if (+form.value.id === 0) {
    await SaveUser(form.value)
    dialogFormVisible.value = false
    loadData()
    ElMessage({
      type: 'success',
      message: '新增成功',
    })
  } else {
    console.log(form.value)

    await UpdateUser(form.value)
    dialogFormVisible.value = false
    loadData()
    ElMessage({
      type: 'success',
      message: '修改成功',
    })
  }
}

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
</script>

<style>
.role-div {
  background: #fff;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
}
.post-div {
  margin: 10px, 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background: #fff;
}
.block {
  margin-left: 30px;
}

/* 上传文件 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
